class MessageParts < ActiveRecord::Base
  belongs_to :phone
  acts_as_mappable :latcolumnname => :latitude, :lngcolumnname => :longitude

#### GEOCODING FIELDS #####
  
  def message
    message = self.read_attribute("message")
    if message.nil?
      message = self.read_attribute("content").gsub("msg ","").gsub("Msg ","").gsub("message ","").gsub("Message ","").gsub("locate ","").gsub("Locate ","").gsub("loc ","").gsub("Loc ","")
      self.write_attribute("message",message)
      self.save!
    end
    self.read_attribute("message")
  end

  # def full_address
  #   self.street_number+" "+self.thoroughfare+" "+self.locality+", "+self.state+", "+self.country+" "+self.postalcode
  # end
  # 
  def street_number
    street_number = read_attribute("street_number")
    street_number ||= ""
  end
  # 
  # def thoroughfare
  #   thoroughfare = read_attribute("thoroughfare")
  #   thoroughfare ||= ""
  # end

  def color
    color = :red if self.message.scan("red")
    color = :green if self.message.scan("green")
    color = :blue if self.message.scan("blue")
  end

  def re_geocode
      geo = GeoKit::GeoLoc.geocode(self.address)
      errors.add(:address, "Could not Geocode address") if !geo.success
      # self.lat, self.lng = geo.lat,geo.lng if geo.success
      if geo.success
        self.address = geo.full_address
        self.country = geo.country_code
        self.state = geo.state
        self.locality = geo.city
        self.street_number = geo.street_number unless geo.street_number.nil?
        self.thoroughfare = geo.street_name
        self.postalcode = geo.zip
        self.accuracy = geo.precision

        self.latitude = geo.lat
        self.longitude = geo.lng
        self.ping_type = 0
        self.save!
      end
  end
  
  def diameter
    diam = (100/(Time.now - self.created_at))
    if diam < 0
      0
    else
      diam
    end
  end 
  
end
